package com.monkey.server.sync;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;

import com.monkey.model.Address;
import com.monkey.model.Node;
import com.monkey.netty.client.NettyClient;
import com.monkey.server.config.ClusterProperties;
import com.monkey.util.IPUtil;

public class ClusterContext {
    private static int timeOut = 5000;
    
    private static List<Address> addresses = new ArrayList<>();
    // 已同步的节点
    private static List<Node> nodes = new ArrayList<>();
    // 同步失败的异常目标节点
//    private static List<Node> failNodes = new ArrayList<>();
    //
    private static Map<Address, NettyClient> addressCache = new HashMap<>();
    
    public static List<Node> getNodes() {
        return nodes;
    }

    public static void setNodes(List<Node> nodes) {
        ClusterContext.nodes = nodes;
    }
    
    public static List<Address> getAddresses() {
        return addresses;
    }
    
    public static NettyClient getNettyClient(Address address) {
        NettyClient nettyClient = null;
        if(!addressCache.containsKey(address)) {
            String host = address.getHost();
            int port = address.getPort();
            nettyClient = new NettyClient(host , port, timeOut);
            // putIfAbsent 该场景下是否需要考虑并发？ 
            addressCache.putIfAbsent(address, nettyClient);
        }
        return nettyClient;
    }
    
    public static void init(ClusterProperties clusterProperties) {
        Node self = new Node();
        Address address = new Address(IPUtil.getLocalIP(), clusterProperties.getNettyport());
        self.setAddress(address );
        self.setNodeCode(clusterProperties.getNodeCode());
        self.setNodeName(clusterProperties.getNodeName());
        
        synchronized (nodes) {
            if(!nodes.contains(self)) {
                nodes.add(self);
            }
        }
    }
    
    private ClusterContext() {}

}
